package com.android.djlmapp.activity.kaika;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.kaika.MyPhotoAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.ShouDongDialog;
import com.android.djlmapp.listener.face.FaceResultBackListener;
import com.android.djlmapp.listener.kaika.ShouDongListListener;
import com.android.djlmapp.listener.read.GetPhotoUrlListener;
import com.android.djlmapp.listener.read.SubReadDataListener;
import com.android.djlmapp.model.eventbus.FaceRzInfo;
import com.android.djlmapp.model.kaika.CardBean;
import com.android.djlmapp.model.kaika.GetFaceDataInfo;
import com.android.djlmapp.model.kaika.GetPhotoInfo;
import com.android.djlmapp.model.weight.StepBean;
import com.android.djlmapp.tools.facetools.FaceUtils;
import com.android.djlmapp.tools.global.BasisTimesUtils;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.kaika.SubReadCardDataUtils;
import com.android.djlmapp.tools.read.GetPhotoUrlUtils;
import com.android.djlmapp.view.HorizontalStepView;
import com.android.djlmapp.view.NoScrollGridView;
import com.android.readcard.activity.ReadCardActivity;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.dialog.MyUsualyDialog;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.ImageTools;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.uitl.TConstant;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;

import static com.android.djlmapp.tools.facetools.FaceUtils.LIVENESS_CODE3;

public class ShiMingRengZhengActivity extends BaseActivity {

    @BindView(R.id.sm_step_view)
    HorizontalStepView smStepView;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.shiming_name)
    TextView shimingName;
    @BindView(R.id.shiming_sex)
    TextView shimingSex;
    @BindView(R.id.shiming_nation)
    TextView shimingNation;
    @BindView(R.id.shiming_month)
    TextView shimingMonth;
    @BindView(R.id.shiming_address)
    TextView shimingAddress;
    @BindView(R.id.shiming_cardnum)
    TextView shimingCardnum;
    @BindView(R.id.shiming_office)
    TextView shimingOffice;
    @BindView(R.id.shiming_yxdata)
    TextView shimingYxdata;
    @BindView(R.id.iv_takephoto)
    TextView ivTakephoto;
    @BindView(R.id.iv_readcard)
    TextView ivReadcard;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.shiming_view)
    View shimingView;
    @BindView(R.id.shiming_photo)
    ImageView shimingPhoto; // 身份证头像
    @BindView(R.id.ll_shiming_read)
    LinearLayout llShimingRead; // 读卡界面
    @BindView(R.id.gv_photo)
    NoScrollGridView gvPhoto;
    @BindView(R.id.ll_shangchuanLlAll)
    LinearLayout llShangchuanLlAll;
    @BindView(R.id.ll_shibie_all)
    LinearLayout llShibieAll;
    @BindView(R.id.shiming_year)
    TextView shimingYear;
    @BindView(R.id.shiming_day)
    TextView shimingDay;

    @BindView(R.id.ll_take_photo)
    LinearLayout llTakePhoto;
    @BindView(R.id.ed_hzname)
    EditText edHzname;
    @BindView(R.id.ed_hznum)
    EditText edHznum;
    @BindView(R.id.tv_hztime)
    TextView tvHztime;
    @BindView(R.id.tv_hzsex)
    TextView tvHzsex;
    @BindView(R.id.ed_hzaddress)
    EditText edHzaddress;
    @BindView(R.id.ll_gatxz)
    LinearLayout llGatxz;
    @BindView(R.id.huzhao)
    TextView huzhao;

    private String hzName = "";
    private String hzNum = "";
    private String hzAddress = "";
    private String hzSex = "";
    private String hzTime = "";

    private String specid = "";
    private String selectPhoneNum = ""; // 选择号码
    private MyPhotoAdapter myPhotoAdapter;
    private ArrayList<GetPhotoInfo.NeedImageBean> needImages = new ArrayList<GetPhotoInfo.NeedImageBean>();
    private MyUsualyDialog dialog;
    private int photoCount = 0; // 需要上传的照片数量
    private String needJbr = "";
    private FaceUtils faceUtils;
    private ShouDongDialog shouDongDialog;
    private int isChengkajihuo = 2;// 1代表选号认证跳转,2代表套餐跳转,3代表成卡激活跳转
    private boolean iskuandai; // 如果是true 就是宽带请求需求照片,false是开卡获取需求照片
    private String huZhaoShow;
    private String isShouDong;
    private boolean isHuZhao = false; // 是不是护照开卡

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shi_ming_reng_zheng);
        ButterKnife.bind(this);
        initView();
        initData();

        if (isChengkajihuo == 2) {
            Event<String> selectNumEvent = new Event<>(EventCodes.EventKaiKaCode.C, "");
            EventBusUtil.sendEvent(selectNumEvent);  // 通知选择号码界面关闭
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ivReadcard.setEnabled(true);
    }

    //点击返回键，返回上一个页面，而不是退出程序
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            FaceRzInfo faceRzInfo = new FaceRzInfo();
            faceRzInfo.setFace_image(""); // 人脸识别照片
            faceRzInfo.setFace_ok(""); // 认证结果 1 成功  2 失败
            faceRzInfo.setSfz_card("");
            faceRzInfo.setSfz_name("");
            faceRzInfo.setSfzPhoto(""); // 身份证头像

            faceRzInfo.setAddress("");
            faceRzInfo.setTime("");
            faceRzInfo.setSex("");
            Event<FaceRzInfo> events = new Event<>(EventCodes.EventFaceCode.A, faceRzInfo);
            EventBusUtil.sendEvent(events);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("实名认证");

        // 根据首页的数据判断拍照按钮是否显示
        isShouDong = PrefUtils.getString(ConstantsValue.ISINPUTIDCARD, "");
        huZhaoShow = PrefUtils.getString(ConstantsValue.ISINPUTHUZHAO, "");

        if ("2".equals(huZhaoShow)) {
            huzhao.setVisibility(View.VISIBLE);
        } else {
            huzhao.setVisibility(View.GONE);
        }

        if ("1".equals(isShouDong)) {
            ivTakephoto.setVisibility(View.VISIBLE);
        } else {
            ivTakephoto.setVisibility(View.INVISIBLE);
        }

        dialog = new MyUsualyDialog(ShiMingRengZhengActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                gvPhoto.setEnabled(false);
                tvNext.setEnabled(false);
                flagPhoto = position + "";
                String image_key = needImages.get(position).getImage_key();
                Log.e("项目异常", "------image_key------" + image_key);
                if (position == 0) {
                    showPhotoDialog(position, image_key); // 初始化拍照弹窗
                } else {
                    if (successFlag != null) {
                        if (successFlag.get(position - 1 + "")) { // 如果前面的照片上传了就可以拍照,不然提示上传上一张照片
                            showPhotoDialog(position, image_key); // 初始化拍照弹窗

                        } else {
                            gvPhoto.setEnabled(true);
                            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请上传"
                                    + list.get(position - 1));
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        changeProgess(true, 1, 0, 0);
        //  显示读卡界面,隐藏拍照界面,隐藏验证界面

        specid = getIntent().getStringExtra("SPECID");
        isChengkajihuo = getIntent().getIntExtra("CHENGKAJIHUO", 2);
        selectPhoneNum = getIntent().getStringExtra("selectPhoneNum");
        iskuandai = getIntent().getBooleanExtra("ISKUANDAI", false);
        if (specid == null) {
            specid = "";
        }
        if (selectPhoneNum == null) {
            selectPhoneNum = "";
        }
    }

    @Override
    public void btnBack() {
        FaceRzInfo faceRzInfo = new FaceRzInfo();
        faceRzInfo.setFace_image(""); // 人脸识别照片
        faceRzInfo.setFace_ok(""); // 认证结果 1 成功  2 失败
        faceRzInfo.setSfz_card("");
        faceRzInfo.setSfz_name("");
        faceRzInfo.setSfzPhoto(""); // 身份证头像

        faceRzInfo.setAddress("");
        faceRzInfo.setTime("");
        faceRzInfo.setSex("");
        Event<FaceRzInfo> events = new Event<>(EventCodes.EventFaceCode.A, faceRzInfo);
        EventBusUtil.sendEvent(events);
        finish();
    }

    /**
     * @param one   1代表进心中,0代表未进行
     * @param two
     * @param three
     */
    private void changeProgess(boolean isAdd, int one, int two, int three) {
        List<StepBean> stepsBeanList = new ArrayList<>();

        if (isAdd) {
            StepBean stepBean0 = new StepBean("身份认证", one);
            StepBean stepBean1 = new StepBean("上传照片", two);
            StepBean stepBean2 = new StepBean("脸部识别", three);

            stepsBeanList.add(stepBean0);
            stepsBeanList.add(stepBean1);
            stepsBeanList.add(stepBean2);
        } else {
            StepBean stepBean0 = new StepBean("身份认证", one);
            StepBean stepBean1 = new StepBean("上传照片", two);

            stepsBeanList.add(stepBean0);
            stepsBeanList.add(stepBean1);
        }

        smStepView
                .setStepViewTexts(stepsBeanList)//总步骤
                .setTextSize(12)//set textSize
                .setStepsViewIndicatorCompletedLineColor(ContextCompat.getColor(getActivity(), R.color.homeTitleBottom))//设置StepsViewIndicator完成线的颜色
                .setStepsViewIndicatorUnCompletedLineColor(ContextCompat.getColor(getActivity(), R.color.homeTitleBottom))//设置StepsViewIndicator未完成线的颜色
                .setStepViewComplectedTextColor(ContextCompat.getColor(getActivity(), R.color.homeTextDanGray))//设置StepsView text完成的颜色
                .setStepViewUnComplectedTextColor(ContextCompat.getColor(getActivity(), R.color.homeTextDanGray))//设置StepsView text未完成的颜色
                .setStepsViewIndicatorCompleteIcon(ContextCompat.getDrawable(getActivity(), R.mipmap.kk_smrz_ok))//设置已完成图标
                .setStepsViewIndicatorDefaultIcon(ContextCompat.getDrawable(getActivity(), R.mipmap.kk_smrz_no))//设置默认图标
                .setStepsViewIndicatorAttentionIcon(ContextCompat.getDrawable(getActivity(), R.mipmap.kk_smrz_no));//设置进行中图标
    }

    @OnClick({R.id.iv_takephoto, R.id.huzhao, R.id.tv_hztime, R.id.tv_hzsex, R.id.iv_readcard, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_hztime: // 选择时间
                String stringTimeOfYMD = BasisTimesUtils.getDeviceTimeOfYMD();
                final String[] split = stringTimeOfYMD.split("-");
                // 日期滚动弹窗
                BasisTimesUtils.showDatePickerDialog(ShiMingRengZhengActivity.this,
                        BasisTimesUtils.THEME_HOLO_LIGHT, "请选择年月日", Integer.parseInt(split[0]), Integer.parseInt(split[1]),
                        Integer.parseInt(split[2]), new BasisTimesUtils.OnDatePickerListener() {

                            @Override
                            public void onConfirm(int year, int month, int dayOfMonth) {
                                if (year >= Integer.parseInt(split[0])) {
                                    if (month >= Integer.parseInt(split[1])) {
                                        if (dayOfMonth >= Integer.parseInt(split[2])) {
                                            tvHztime.setText(year + "-" + month + "-" + dayOfMonth);
                                        } else {
                                            tvHztime.setText("");
                                            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请选择正确日期");
                                        }
                                    } else {
                                        ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请选择正确日期");
                                    }
                                } else {
                                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请选择正确日期");
                                }
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
                break;
            case R.id.tv_hzsex: // 选择性别
                // 性别弹窗
                // 创建弹窗对象
                AlertDialog.Builder builder = new AlertDialog.Builder(ShiMingRengZhengActivity.this);
                // 自定义弹窗布局
                View convertView = View.inflate(getApplicationContext(), R.layout.sex_dialog,
                        null);
                // 将自定义布局设置给dialog
                builder.setView(convertView);
                // 获取dialog
                final AlertDialog alertDialog = builder.create();

                TextView tv_nan = (TextView) convertView.findViewById(R.id.tv_nan);
                TextView tv_nv = (TextView) convertView.findViewById(R.id.tv_nv);

                // 显示弹窗
                alertDialog.setCancelable(false);
                alertDialog.show();

                tv_nan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (alertDialog != null) {
                            alertDialog.dismiss();
                        }
                        tvHzsex.setText("男");
                    }
                });
                tv_nv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (alertDialog != null) {
                            alertDialog.dismiss();
                        }
                        tvHzsex.setText("女");
                    }
                });
                break;
            case R.id.huzhao: // 护照
                sfzSuccess = false;

                PrefUtils.putString("FACE_HUZHAO", "");
                PrefUtils.putString("BACK_HUZHAO", "");
                PrefUtils.putString("JBR_IDNUM", ""); // 保存经办人身份证号
                if (isHuZhao) {
                    Log.e("项目异常护照", "------转换到身份证之后------");
                    isHuZhao = false;
                    bluetoothName = "";
                    // 转换到身份证之后
                    edHzname.setText("");
                    edHznum.setText("");
                    edHzaddress.setText("");
                    edHzname.setHint("请输入护照/港澳通行证姓名");
                    edHznum.setHint("请输入护照/港澳通行证号码");
                    edHzaddress.setHint("请输入正确的联系地址");

                    tvHzsex.setText("请选择客户性别");
                    tvHztime.setText("请选择护照/港澳通行证有效时间");

                    changeProgess(true, 1, 0, 0);
                    llTakePhoto.setVisibility(View.VISIBLE);
                    llGatxz.setVisibility(View.GONE);
                    ivReadcard.setVisibility(View.VISIBLE);
                    if ("1".equals(isShouDong)) {
                        // 显示拍照
                        ivTakephoto.setVisibility(View.VISIBLE);
                    } else {
                        // 不显示拍照
                        ivTakephoto.setVisibility(View.GONE);
                    }
                    huzhao.setText("护照/港澳通行证");
                } else {
                    Log.e("项目异常护照", "------转换到护照之后------");
                    isHuZhao = true;
                    bluetoothName = "护照";
                    // 转换到护照之后
                    cardNum = ""; // 身份证号码
                    cardName = ""; // 身份证姓名
                    cardIdPath = ""; // 身份证头像路径
                    cardPhotoUrl = ""; // 身份证头像url

                    shimingName.setText("");
                    shimingSex.setText("");
                    shimingNation.setText("");
                    shimingYear.setText("");
                    shimingMonth.setText("");
                    shimingDay.setText("");
                    shimingAddress.setText("");
                    shimingCardnum.setText("");
                    shimingOffice.setText("");
                    shimingYxdata.setText("");
                    shimingPhoto.setImageBitmap(null);

                    PrefUtils.putString("NEED_JBR", "0");
                    ivReadcard.setText("扫描证件");
                    isJbr = false;
                    needJbr = "";

                    changeProgess(false, 1, 0, 0);

                    llTakePhoto.setVisibility(View.GONE);
                    llGatxz.setVisibility(View.VISIBLE);
                    ivReadcard.setVisibility(View.GONE);
                    huzhao.setVisibility(View.VISIBLE);
                    ivTakephoto.setVisibility(View.VISIBLE);
                    huzhao.setText("第二代身份证");
                }
                break;
            case R.id.iv_takephoto: // 拍照获取身份信息
                ivTakephoto.setEnabled(false);
                isTake = true;
                shouDongGetReadCard();
                break;
            case R.id.iv_readcard:  // 读卡获取身份信息
                ivReadcard.setEnabled(false);
                isTake = false;
                startActivity(new Intent(ShiMingRengZhengActivity.this, ReadCardActivity.class));
                break;
            case R.id.tv_next: // 下一步
                goToNext();
                break;
        }
    }

    /**
     * 下一步
     */
    private void goToNext() {
        if (llShibieAll.getVisibility() == View.VISIBLE) {
            // 跳转活体/静态检测前 tvNext.setText("开始验证");
            tvNext.setEnabled(false);
            startFaceNet();
        } else {
            if (isHuZhao) {
                hzName = edHzname.getText().toString().trim();
                hzNum = edHznum.getText().toString().trim();
                hzAddress = edHzaddress.getText().toString().trim();

                hzSex = tvHzsex.getText().toString().trim();
                hzTime = tvHztime.getText().toString().trim();


                if (TextUtils.isEmpty(hzName)) {
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请输入护照/港澳通行证姓名");
                    return;
                }
                if (TextUtils.isEmpty(hzNum)) {
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请输入护照/港澳通行证号码");
                    return;
                }
                if (TextUtils.isEmpty(hzAddress)) {
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请输入正确的联系地址");
                    return;
                }
                if (hzTime.contains("请选择")) {
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请选择护照/港澳通行证有效时间");
                    return;
                }
                if (hzSex.contains("请选择")) {
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "请选择客户性别");
                    return;
                }
            }
            if (sfzSuccess) {
                if (needImages.size() > 0) {
                    // 如果身份信息确认完成并且拍照上传已经完成 隐藏读卡界面,隐藏拍照界面,显示验证界面 changeProgess(1, 1, 1);
                    if (flagList.size() == photoCount) {
                        if (isHuZhao) {
                            FaceRzInfo faceRzInfo = new FaceRzInfo();
                            faceRzInfo.setFace_image(""); // 人脸识别照片
                            faceRzInfo.setFace_ok("2"); // 认证结果 1 成功  2 失败
                            faceRzInfo.setSfz_card(hzNum);
                            faceRzInfo.setSfz_name(hzName);
                            faceRzInfo.setSfzPhoto(""); // 身份证头像

                            faceRzInfo.setAddress(hzAddress);
                            faceRzInfo.setTime(hzTime);
                            faceRzInfo.setSex(hzSex);
                            Event<FaceRzInfo> event = new Event<>(EventCodes.EventFaceCode.A, faceRzInfo);
                            EventBusUtil.sendEvent(event);
                            finish();
                        } else {
                            translationAnim();
                            changeProgess(true, 1, 1, 1);
                            llShimingRead.setVisibility(View.GONE);
                            llShangchuanLlAll.setVisibility(View.GONE);
                            llShibieAll.setVisibility(View.VISIBLE);
                            tvNext.setText("开始验证");
                        }
                    } else {
                        ToastUtils.showShortToast(this, "请确认所有照片上传完毕");
                    }
                } else {
                    // 如果身份信息确认完成  隐藏读卡界面,显示拍照界面,隐藏验证界面 changeProgess(1, 1, 0);
                    // 获取经办人状态值
                    if ("1".equals(needJbr)) {
                        ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "未成年,请扫描经办人证件");
                    } else {
                        // 加载进度条

                        if (isHuZhao) {
                            hzName = edHzname.getText().toString().trim();
                            hzNum = edHznum.getText().toString().trim();
                            hzAddress = edHzaddress.getText().toString().trim();

                            hzSex = tvHzsex.getText().toString().trim();
                            hzTime = tvHztime.getText().toString().trim();

                            translationAnim();
                            changeProgess(false, 1, 1, 0);
                            llShimingRead.setVisibility(View.GONE);
                            llShangchuanLlAll.setVisibility(View.VISIBLE);
                            llShibieAll.setVisibility(View.GONE);

                        } else {
                            hzName = "";
                            hzNum = "";
                            hzAddress = "";
                            hzSex = "";
                            hzTime = "";

                            translationAnim();
                            changeProgess(true, 1, 1, 0);
                            llShimingRead.setVisibility(View.GONE);
                            llShangchuanLlAll.setVisibility(View.VISIBLE);
                            llShibieAll.setVisibility(View.GONE);
                        }


                        photoMsgNet();
                    }
                }
            } else {
                ToastUtils.showShortToast(this, "身份信息未校验");
            }
        }
    }

    /**
     * 拍照获取身份信息
     */
    private void shouDongGetReadCard() {
        if (isHuZhao) {
            shouDongDialog = new ShouDongDialog(
                    ShiMingRengZhengActivity.this, R.layout.shoudong_dialog, dialogListener);
        } else {
            shouDongDialog = new ShouDongDialog(
                    ShiMingRengZhengActivity.this, R.layout.shoudong_dialog_card, dialogListener);
        }
        shouDongDialog.setCanceledOnTouchOutside(false);
        shouDongDialog.show();
        shouDongDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                ivTakephoto.setEnabled(true);
                isTake = false;
            }
        });
    }

    ShouDongListListener dialogListener = new ShouDongListListener() {

        @Override
        public void onCancleOrder(String str, String needJb) {
            ivTakephoto.setEnabled(true);
            if (TextUtils.isEmpty(str)) {
                sfzSuccess = true;
                bluetoothName = "拍照";
            } else {
                needJbr = needJb;
                isHuoTi = true;
                try {
                    Gson gson = new Gson();
                    final CardBean cardBean = gson.fromJson(str, CardBean.class);
                    shimingName.setText(cardBean.getName());
                    shimingSex.setText(cardBean.getSex());
                    shimingNation.setText(cardBean.getNation());
                    shimingYear.setText(cardBean.getYear());
                    shimingMonth.setText(cardBean.getMonth());
                    shimingDay.setText(cardBean.getDay());
                    shimingAddress.setText(cardBean.getAddress());
                    shimingCardnum.setText(cardBean.getIdcardno());
                    shimingOffice.setText(cardBean.getGrantdept());
                    shimingYxdata.setText(cardBean.getValid_date());

                    Glide.with(ShiMingRengZhengActivity.this).load(cardBean.getPhoto()).into(shimingPhoto);

                    sfzSuccess = true;
                    bluetoothName = "拍照";

                    if ("1".equals(needJb)) {
                        ivTakephoto.setText("拍照经办人证件");
                    } else {
                        ivTakephoto.setText("手动拍照");
                    }
//                    if ("王旭阳".equals(cardBean.getName())) {
//                        ivTakephoto.setText("经办人照");
//                    } else {
//                        ivTakephoto.setText("手动拍照");
//                    }
                    OkGo.<Bitmap>get(cardBean.getPhoto()).execute(new BitmapCallback() {

                        @Override
                        public void onSuccess(Response<Bitmap> response) {
                            getIdPath(response.body(), cardBean, needJb);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    sfzSuccess = false;
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "身份信息解析异常");
                }
            }
        }

        @Override
        public void onZhengOrFanOrder(int type) {
            isHuoTi = false;
            ivTakephoto.setEnabled(true);
            photoType = type;
            takePhoto();
        }
    };

    private void getIdPath(Bitmap bitmap, CardBean cardBean, String needJbr) {
        String path = BleGlobUtils.saveIDIcon(bitmap);
        Log.e("项目异常", "------获取信息成功path------" + path);
        if (path.contains("异常")) {
            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "保存头像到本地失败");
        } else {
            if ("1".equals(needJbr)) {
                isJbr = true;
                cardIdPath = path;
                cardPhotoUrl = cardBean.getPhoto();
                cardNum = cardBean.getIdcardno();
                cardName = cardBean.getName();
                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "未成年,请扫描经办人证件");

            } else {
                if (isJbr) {
                    PrefUtils.putString("JBR_IDNUM", cardBean.getIdcardno()); // 保存经办人身份证号
                    Log.e("项目异常", "------GET_CARD_INFO------" + cardBean.getIdcardno());
                    // 需要经办人的直接跳转
                    isJbr = false;
                    // 加载进度条
                    dialog.show();
                    translationAnim();
                    changeProgess(true, 1, 1, 0);
                    llShimingRead.setVisibility(View.GONE);
                    llShangchuanLlAll.setVisibility(View.VISIBLE);
                    llShibieAll.setVisibility(View.GONE);
                    photoMsgNet();
                } else {
                    PrefUtils.putString("JBR_IDNUM", "");
                    cardPhotoUrl = cardBean.getPhoto();
                    cardNum = cardBean.getIdcardno();
                    cardName = cardBean.getName();
                    cardIdPath = path;
                }
            }
        }
        Log.e("项目异常", cardIdPath + "------获取信息成功------" + cardPhotoUrl);
    }

    // 平移动画
    private void translationAnim() {
        llShimingRead.setTranslationX(0f);
        ViewCompat.animate(llShimingRead)
                .translationXBy(-1000f)
                .setDuration(1500)
                .setInterpolator(new OvershootInterpolator())
                .start();
    }

    private Boolean sfzSuccess = false; // 身份信息上传成功与否标记
    private String bluetoothName = ""; // 蓝牙名称
    private boolean isJbr = false;


    private String cardNum = ""; // 身份证号码
    private String cardName = ""; // 身份证姓名
    private String cardIdPath = ""; // 身份证头像路径
    private String cardPhotoUrl = ""; // 身份证头像url

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventReadCardCode.A: // 读卡
                dialog.show();
                BackReadInfo data = (BackReadInfo) event.getData();
                ReadCardInfo readInfo = data.getInfo();
                CardData cardData = data.getCardData();
                String chuanma = data.getChuanma();

                //成功返回数据之后先判断是读卡还是补卡
                // 补卡直接处理
                // 读卡就先提交数据(cardData读卡数据,chuanma串码,readInfo.getIdPath()头像保存路径)到服务器
                submitReadCardData(readInfo, cardData, chuanma);
                break;
        }

    }

    /**
     * 提交读卡数据
     *
     * @param readInfo
     * @param cardData
     * @param chuanma
     */
    private void submitReadCardData(ReadCardInfo readInfo, CardData cardData, String chuanma) {
        // 先将文本赋值
        shimingName.setText(readInfo.getName());
        shimingSex.setText(readInfo.getSex());
        shimingNation.setText(readInfo.getNation());
        shimingYear.setText(readInfo.getBirth_year());
        shimingMonth.setText(readInfo.getBirth_month());
        shimingDay.setText(readInfo.getBirth_day());
        shimingAddress.setText(readInfo.getAddress());
        shimingCardnum.setText(readInfo.getId_num());
        shimingOffice.setText(readInfo.getSign_office());
        shimingYxdata.setText(readInfo.getSign_data());

        // 上传身份信息获取经办人数据
        SubReadCardDataUtils.getJingBanRenData(readInfo, cardData, chuanma, new SubReadDataListener() {
            @Override
            public void subPhotoSuc(String needJb, String photoUrl) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                // 身份信息上传成功
                needJbr = needJb;
                // 成功获取到头像url
                jingBanRenData(readInfo, photoUrl);
            }

            @Override
            public void subErr(String msg) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, msg);
            }
        });
    }

    /**
     * 处理经办人业务逻辑
     *
     * @param readInfo
     * @param photoUrl
     */
    private void jingBanRenData(ReadCardInfo readInfo, String photoUrl) {

        sfzSuccess = true; // 头像上传完成才可以设为true

        // 设置头像
        Glide.with(ShiMingRengZhengActivity.this).load(photoUrl).into(shimingPhoto);

        bluetoothName = readInfo.getBluetoohName();
        PrefUtils.putString("BluetoothName", bluetoothName); // 读取信息的蓝牙设备
        Log.e("项目异常", needJbr + "----submitReadCardData------" + readInfo.getId_num());
        if ("1".equals(needJbr)) {
            // 如果需要经办人,先把活体检测需要的字段设置全局便变量
            isJbr = true;
            cardNum = readInfo.getId_num();
            cardPhotoUrl = photoUrl;
            cardName = readInfo.getName();
            cardIdPath = readInfo.getIdPath();
            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "未成年,请扫描经办人证件");
            ivReadcard.setText("扫经办人");
        } else {
            ivReadcard.setText("扫描证件");
            if (isJbr) {
                PrefUtils.putString("JBR_IDNUM", cardNum);
                // 如果不需要经办人,先判断有没有处理过经办人的逻辑,如果处理过就直接跳转到下一步,
                // 需要经办人的直接跳转
                // 加载进度条
                translationAnim();
                changeProgess(true, 1, 1, 0);
                llShimingRead.setVisibility(View.GONE);
                llShangchuanLlAll.setVisibility(View.VISIBLE);
                llShibieAll.setVisibility(View.GONE);
                isJbr = false;
                // 加载进度条
                photoMsgNet(); // 获取拍照界面的信息
            } else {
                PrefUtils.putString("JBR_IDNUM", "");
                // 如果没处理过,就说明是成年人,需要重新设置全局变量
                cardNum = readInfo.getId_num();
                cardPhotoUrl = photoUrl;
                cardName = readInfo.getName();
                cardIdPath = readInfo.getIdPath();
            }
        }
    }

    /**
     * 获取实名拍照数据
     */
    private void photoMsgNet() {
        dialog.show();
        MyApplication.getInstance().getHttpTools().getPhotoMsg(iskuandai, selectPhoneNum, specid, cardNum,
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            parsePhotoMsgJson(response.body());
                        } catch (Exception e) {
                            Log.e("项目异常", "------1------" + e.toString());
                            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "数据解析异常");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "网络或服务器错误请返回重新进入");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        // 获取拍照信息后就开始获取活体检测授权
                        faceUtils = new FaceUtils(ShiMingRengZhengActivity.this,
                                "1", cardName, cardNum, cardIdPath, cardPhotoUrl,
                                new FaceResultBackListener() {
                                    @Override
                                    public void backCode(int backCode) {
                                        if (backCode == 1) {
                                            Event<String> selectNumEvent = new Event<>(EventCodes.EventKaiKaCode.C, "");
                                            EventBusUtil.sendEvent(selectNumEvent);  // 通知选择号码界面关闭
                                            finish();
                                        }
                                    }
                                });
                        faceUtils.netWorkWarranty();// 取活体检测授权
                    }
                });
    }

    /**
     * 获取活体检测数据
     * 如果活体检测未获取到联网授权还需要设置 tvNext.setEnabled(true);
     */
    private void startFaceNet() {
        //请求人脸识别类型的参数   "face_type":1 //1  活体检测 2 静态检测
        Log.e("项目异常specid", "------specid------" + specid);
        MyApplication.getInstance().getHttpTools().getFaceData(specid, new StringCallback() {

            @Override
            public void onSuccess(Response<String> response) {
                try {
                    Gson gson = new Gson();
                    GetFaceDataInfo faceInfo = gson.fromJson(response.body(), GetFaceDataInfo.class);
                    if (faceInfo != null) {
                        if (faceInfo.getCode() < 1000) {
                            String textnumber = faceInfo.getFace_type();
//                            if (faceUtils.isShouQuan()) {
//                                faceUtils.jumpActivity();
//                            } else {
//                                // 授权失败跳转获取授权界面
//                                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "活体检测授权失败,请重新获取授权");
//                            }
                            if (isHuoTi) {
                                // 如果是拍照流程就全部活体检测
                                // 旧活体检测
                                if (faceUtils.isShouQuan()) {
                                    faceUtils.jumpActivity();
                                } else {
                                    // 授权失败跳转获取授权界面
                                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "活体检测授权失败,请重新获取授权");
                                }
                            } else {
                                if (textnumber.equals("1")) {
                                    // 开始人脸识别
                                    if (faceUtils.isShouQuan()) {
                                        faceUtils.jumpActivity();
                                    } else {
                                        // 授权失败跳转获取授权界面
                                        ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "活体检测授权失败,请重新获取授权");
                                    }
                                } else if (textnumber.equals("2")) {
                                    // 人脸对比成功后清空存储的图片
                                    Intent intentLiveness = new Intent(ShiMingRengZhengActivity.this,
                                            FaceCarmerActivity.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putString("FILE_PHOTO", cardPhotoUrl);
                                    bundle.putString("USER_NAME", cardName);
                                    bundle.putString("USER_CARD", cardNum);
                                    bundle.putString("BluetoothName", bluetoothName);

                                    intentLiveness.putExtras(bundle);
                                    startActivityForResult(intentLiveness, LIVENESS_CODE3);
                                }
                            }
                        } else {
                            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, faceInfo.getMsg());
                        }
                    }
                } catch (Exception e) {
                    Log.e("项目异常", "-----ShiMingRengZhengActivity-数据解析异常------" + e.toString());
                    ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "数据解析异常");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "网络或服务器错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                tvNext.setEnabled(true);
            }
        });
    }

    private boolean isTake = false; // 判断是不是拍照获取信息,获取到URL后设置为false
    private boolean isHuoTi = false; // 最终是不是活体检测
    private int photoType;

    private Map<Integer, String> flagList = new HashMap<Integer, String>(); // 照片上传成功url集合
    private ArrayList<String> list = new ArrayList<String>(); // 照片名称集合
    private String flagPhoto = ""; // 存储照片位置的标记

    private HashMap<String, String> bitmapList = new HashMap<String, String>(); // 存储照片路径的集合
    private HashMap<String, Boolean> successFlag = new HashMap<String, Boolean>(); // 标记第几张照片是成功上传的
    public static final String key = "key";     // 保存照片键
    public static final String value = "value"; // 保存照片值
    private int gongAnPosition = -1;

    private void parsePhotoMsgJson(String json) {
        Gson gson = new Gson();
        GetPhotoInfo getPhotoInfo = gson.fromJson(json, GetPhotoInfo.class);
        if (getPhotoInfo != null) {
            if (getPhotoInfo.getCode() < 1000) {
                needImages.clear();
                list = new ArrayList<String>();
                photoCount = getPhotoInfo.getCount();
                List<GetPhotoInfo.NeedImageBean> need_image = getPhotoInfo.getNeed_image();
                needImages.addAll(need_image);
                if (needImages != null && needImages.size() > 0) {
                    // 逻辑判断
                    for (int i = 0; i < needImages.size(); i++) {
                        successFlag.put(i + "", false);
                        list.add(needImages.get(i).getImage_name());

                        // 保存 用户上传的照片(正,反,手持,公安)
                        PrefUtils.putString(key + i, needImages.get(i).getImage_key());
                    }
                    myPhotoAdapter = new MyPhotoAdapter(ShiMingRengZhengActivity.this, list, bitmapList);
                    gvPhoto.setAdapter(myPhotoAdapter);
                }
            } else {
                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, getPhotoInfo.getMsg());
            }
        } else {
            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "未获取到数据22");
        }
    }
    //**********************************************实现拍照**************************************************************

    private BaseBottomDialog myDialog = null;

    //拍照相册选择dialog
    private void showPhotoDialog(final int index, final String image_key) {
        myDialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.activity_my_photo_edit)
                .setDimAmount(0.5f)            // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)     // 点击外部区域是否关闭，默认true
                .setTag("BottomDialog")     // 设置DialogFragment的tag
                .setViewListener(new BottomDialog.ViewListener() {      // 可以进行一些必要对View的操作
                    @Override
                    public void bindView(View v) {
                        dialogClick(v, index, image_key);
                    }
                })
                .show();

    }

    private void dialogClick(View v, final int index, String image_key) {
        gvPhoto.setEnabled(true);
        View user_take_photo = v.findViewById(R.id.user_take_photo);
        View user_select_from_lib = v.findViewById(R.id.user_select_from_lib);
        View user_photo_cancel = v.findViewById(R.id.user_photo_cancel);
        View split = v.findViewById(R.id.split);

        if ("police_image".equals(image_key)) {
            user_select_from_lib.setVisibility(View.VISIBLE);
            split.setVisibility(View.VISIBLE);
        } else {
            user_select_from_lib.setVisibility(View.GONE);
            split.setVisibility(View.GONE);
        }

        user_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gvPhoto.setEnabled(false);
                if (myDialog != null) {
                    myDialog.dismiss();
                }
                gongAnPosition = index;
                takePhoto();
            }
        });
        user_select_from_lib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gvPhoto.setEnabled(false);
                if (myDialog != null) {
                    myDialog.dismiss();
                }
                gongAnPosition = index;
                choosePhoto();
            }
        });
        user_photo_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gvPhoto.setEnabled(true);
                if (myDialog != null) {
                    myDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void takeSuccess(TResult result) {
        ArrayList<TImage> images = result.getImages();

        showImg(images);
    }

    /**
     * 上传照片
     *
     * @param images
     */
    private void showImg(ArrayList<TImage> images) {
        String compressPath = images.get(0).getCompressPath();
        if (compressPath != null && !TextUtils.isEmpty(compressPath)) {
            Log.e("项目异常", "------showImg------" + compressPath);
            GetPhotoUrlUtils.getPhotoUrl(compressPath, new GetPhotoUrlListener() {
                @Override
                public void backPhotoUrl(int backType, String photoUrl) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    tvNext.setEnabled(true);
                    if (backType == 1) {
                        if (gvPhoto != null) {
                            gvPhoto.setEnabled(true);
                        }
                        if (!TextUtils.isEmpty(photoUrl)) {
                            String filename = "";
                            try {
                                filename = URLEncoder.encode(photoUrl, "UTF-8");
                                if (isTake) {
                                    if (isHuZhao) {
                                        // 保存护照url
                                        if (photoType == 0) {
                                            PrefUtils.putString("FACE_HUZHAO", filename);
                                        } else if (photoType == 1) {
                                            PrefUtils.putString("BACK_HUZHAO", filename);
                                        }
                                    } else {
                                        // 清空护照url
                                        PrefUtils.putString("FACE_HUZHAO", "");
                                        PrefUtils.putString("BACK_HUZHAO", "");
                                    }
                                    // 如果是拍照获取身份信息,还要讲照片设置到控件上
                                    shouDongDialog.setUrl(isHuZhao, photoType, compressPath, filename);
                                } else {
                                    // 上传运营商所需照片
                                    successFlag.put(flagPhoto, true);
                                    flagList.put(gongAnPosition + 1, filename);
                                    bitmapList.put(flagPhoto, compressPath);
                                    Log.e("项目异常", "------flagList.size()------" + flagList.size());
                                    PrefUtils.putString(value + gongAnPosition, filename);
                                    PrefUtils.putInt("PHOT_LISTS", flagList.size()); // 保存拍照数量,根据键key取值value
                                    myPhotoAdapter.update(list, bitmapList);
                                }
                            } catch (Exception e) {
                                Log.e("项目异常", "------编码失败,请重新拍照------" + e.toString());
                                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "编码失败,请重新拍照");
                                e.printStackTrace();
                            }
                        }
                    } else {
                        ToastUtils.showShortToast(ShiMingRengZhengActivity.this, photoUrl);
                    }
                }
            });
        } else {
            if (gvPhoto != null) {
                gvPhoto.setEnabled(true);
            }
            tvNext.setEnabled(true);
            ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "获取路径失败,请重新拍照");
        }
    }

    @Override
    public void takeFail(TResult result, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常takeSuccess", "------takeFail------" + msg);
                if (gvPhoto != null) {
                    gvPhoto.setEnabled(true);
                }
                tvNext.setEnabled(true);
                ToastUtils.showShortToast(ShiMingRengZhengActivity.this, "拍照失败" + msg);
            }
        });
    }

    @Override
    public void takeCancel() {
        Log.e("项目异常", "------takeCancel------");
        tvNext.setEnabled(true);
        if (gvPhoto != null) {
            gvPhoto.setEnabled(true);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e("项目异常", resultCode + "------onActivityResult拍照------" + requestCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == LIVENESS_CODE3) {
                if (data != null) {
                    int backCode = data.getIntExtra("backCode", 0);
                    if (backCode == 1) {
                        finish();
                    }
                }
            } else if (requestCode == TConstant.RC_PICK_PICTURE_FROM_CAPTURE) {
                // 第三方拍照dialog
                dialog.show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        try {
            if (dialog != null) {
                dialog.dismiss();
            }
            ImageTools.deleteAllPhoto(ShiMingRengZhengActivity.this, Environment.getExternalStorageDirectory() + "/temp/");
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

}
